package com.lingjtx.common.core.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

public class FileUtil {

    private static final Logger log = LoggerFactory.getLogger(FileUtil.class);

    /**
     * 在资源文件夹中获取文件路径
     *
     * @param fileName 文件名
     * @return 文件路径
     */
    public static String findFilePath(Class clazz, String fileName) {
        return findFile(clazz, fileName).getPath();
    }

    /**
     * 在资源文件夹中获取文件
     *
     * @param fileName 文件名
     * @return
     */
    public static File findFile(Class clazz, String fileName) {
        return new File(clazz.getClassLoader().getResource(fileName).getPath());
    }

    /**
     * 获取本项目模块下的路径
     *
     * @return
     */
    public static String getResourcePath() {
        return new File(FileUtil.class.getResource("/").getPath()).getPath();
    }

    public static String getResourcePath(String fileName) {
        return findFile(FileUtil.class, fileName).getPath();
    }

    /**
     * 获取fileName所在的资源目录路径
     *
     * @param fileName
     * @return
     */
    public static String getResourceParent(Class clazz, String fileName) {
        return findFile(clazz, fileName).getParent();
    }

    public static String getResourceParent(String fileName) {
        return getResourceParent(FileUtil.class, fileName);
    }

    public static String readFromInputStream(InputStream inputStream) {
        if (inputStream != null) {
            StringBuilder resultStringBuilder = new StringBuilder();
            try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
                String line;
                while ((line = br.readLine()) != null) {
                    resultStringBuilder.append(line);
                }
            } catch (IOException e) {
                log.error("FileUtil readFromInputStream exception:{}", e.getMessage());
            }
            return resultStringBuilder.toString();
        }
        return null;
    }

    public static InputStream readFormPath(String path) {
        if (path != null) {
            return FileUtil.class.getResourceAsStream(path);
        }
        return null;
    }

    public static String read(String path) {
        return readFromInputStream(readFormPath(path));
    }
}
